from __future__ import absolute_import
#import logging
from forest.api import Command, get_tool

class RaidPostInstall(Command):
    ''' Finishes up after create raid.

        Installs a mdadm.conf file in the install root.
    '''
    __register__ = 'commands.install.RaidPostInstall'

    def run(self, config):

        devs = list(config.get_resources().iter_by_type('raid'))
        if not devs:
            return

        #need this cleanup regardless of whether raid is enabled
        install_tree = config.get_install_root()
        with get_tool('system.chroot')(install_tree):
            #disable services auto-enabled by mdadm rpm post-install script
            systemd = get_tool('systemd.Systemd')('/')


            systemd.get_service('mdmonitor.service').disable()
            systemd.get_service('mdmonitor-takeover.service').disable()

            #and lvm2 - not really raid related, but..
            #frankly, would rather just enable removing dead symlinks in cleanup

            #XXX had to remove - fails
            #systemd.get_service('lvm2-monitor.service').disable()
            #import time
            #time.sleep(5)

            mailaddr = config.get('mdmonitor.mailaddr', '')
            program = config.get('mdmonitor.program', '')

            if config.get('use_mdmonitor', False):
                systemd.get_service('mdmonitor.service').enable()
                systemd.get_service('mdmonitor-takeover.service').enable()
            #if config.get('use_lvm2-monitor', False):
            #    systemd.get_service('lvm2-monitor.service').enable()

            raid_lst = []
            for iserr, line in get_tool('system.poll')(['mdadm', '--examine', '--scan']):
                if iserr:
                    continue
                raid_lst.append('%s\n' % line.strip())

            if mailaddr != '':
                raid_lst.append('MAILADDR {}'.format(mailaddr))
            if program != '':
                raid_lst.append('PROGRAM {}'.format(program))

            get_tool('files.write')('/etc/mdadm.conf', ''.join(raid_lst))
